package message.util;

import java.util.function.BiFunction;

public class Chain<T, E> {
	
	private BiFunction<? super T, ? super E, Boolean> func;
	private Chain<T, E> next;
	
	public static <T, E> Chain<T, E> of(BiFunction<? super T, ? super E, Boolean> func) {
		return new Chain<>(func);
	}
	
	private Chain(BiFunction<? super T, ? super E, Boolean> func) {
		this.func = func;
	}
	
	public Chain<T, E> next(BiFunction<? super T, ? super E, Boolean> func) {
		if(this.next != null) this.next.next(func);
		else this.next = new Chain<>(func);
		return this;
	}
	
	public Chain<T, E> run(T t, E e) {
		Chain<T, E> last = this;
		while(last.func.apply(t, e)) 
			if((last = last.next) == null) return null;
		return last;
	}
	
}
